#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
日志管理模块
提供统一的日志配置和管理功能
"""

import logging
import logging.handlers
import os
from pathlib import Path
from typing import Optional

from .config import get_config


class LogManager:
    """日志管理器"""
    
    def __init__(self):
        self._loggers = {}
        self._setup_default_logger()
    
    def _setup_default_logger(self):
        """设置默认日志配置"""
        log_config = get_config('app', {})
        
        # 创建日志目录
        log_file = log_config.get('log_file', 'logs/webdav.log')
        log_dir = Path(log_file).parent
        log_dir.mkdir(parents=True, exist_ok=True)
        
        # 配置根日志器
        root_logger = logging.getLogger()
        root_logger.setLevel(getattr(logging, log_config.get('log_level', 'INFO')))
        
        # 清除现有处理器
        for handler in root_logger.handlers[:]:
            root_logger.removeHandler(handler)
        
        # 文件处理器
        file_handler = logging.handlers.RotatingFileHandler(
            log_file,
            maxBytes=log_config.get('max_log_size', 10 * 1024 * 1024),
            backupCount=log_config.get('log_backup_count', 5),
            encoding='utf-8'
        )
        file_formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        file_handler.setFormatter(file_formatter)
        root_logger.addHandler(file_handler)
        
        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_formatter = logging.Formatter(
            '%(levelname)s - %(name)s - %(message)s'
        )
        console_handler.setFormatter(console_formatter)
        root_logger.addHandler(console_handler)
    
    def get_logger(self, name: str) -> logging.Logger:
        """获取指定名称的日志器"""
        if name not in self._loggers:
            self._loggers[name] = logging.getLogger(name)
        return self._loggers[name]


# 全局日志管理器实例
_log_manager = LogManager()


def get_logger(name: Optional[str] = None) -> logging.Logger:
    """获取日志器"""
    if name is None:
        return logging.getLogger()
    return _log_manager.get_logger(name)


def setup_logging():
    """设置日志配置"""
    _log_manager._setup_default_logger()